// pages/community/community.js
const { get, post } = require('../../utils/api.js')
const { showError, showSuccess, showToast } = require('../../utils/util.js')
const { navigateTo } = require('../../utils/router.js')

Page({
  data: {
    // 当前城市
    currentCity: '全国',
    
    // 筛选标签
    activeFilter: 'recommend',
    
    // 搜索相关
    showSearch: false,
    searchKeyword: '',
    
    // 动态列表
    posts: [],
    loading: false,
    refreshing: false,
    hasMore: true,
    
    // 发布动态
    showCreatePost: false,
    newPostContent: '',
    canPublish: false,
    selectedTopics: [],
    selectedMentions: [],
    
    // 城市选择
    showLocationPicker: false,
    cities: [
      { cityName: '全国', cityCode: 'all', selected: true },
      { cityName: '北京', cityCode: 'beijing', selected: false },
      { cityName: '上海', cityCode: 'shanghai', selected: false },
      { cityName: '广州', cityCode: 'guangzhou', selected: false },
      { cityName: '深圳', cityCode: 'shenzhen', selected: false },
      { cityName: '成都', cityCode: 'chengdu', selected: false },
      { cityName: '杭州', cityCode: 'hangzhou', selected: false },
      { cityName: '南京', cityCode: 'nanjing', selected: false },
      { cityName: '武汉', cityCode: 'wuhan', selected: false },
      { cityName: '西安', cityCode: 'xian', selected: false }
    ],
    
    // 评论弹窗
    showCommentModal: false,
    commentContent: '',
    currentPostId: '',
    
    // 操作菜单
    showActionSheet: false,
    actionSheetActions: [],
    
    // 增强的社区功能
    // 话题相关
    hotTopics: [],
    showTopicPicker: false,
    inputTopics: [],
    
    // 提及相关
    showMentionPicker: false,
    mentionSearchKeyword: '',
    mentionUsers: [],
    inputMentions: [],
    
    // 本地发现
    nearbyPosts: [],
    userLocation: null,
    maxDistance: 10, // 10公里
    
    // 发布增强功能
    showPostEditor: false,
    editorContent: '',
    editorCursorPosition: 0,
    postPrivacy: 'public', // public, friends, private
    enableComments: true,
    enableSharing: true,
    
    // 话题详情
    showTopicDetail: false,
    currentTopic: null,
    topicPosts: [],
    
    // 用户互动
    showUserActions: false,
    selectedUser: null,
    
    // 内容管理
    reportTypes: [
      { id: 'spam', label: '垃圾信息' },
      { id: 'inappropriate', label: '不当内容' },
      { id: 'harassment', label: '骚扰行为' },
      { id: 'fake', label: '虚假信息' },
      { id: 'other', label: '其他' }
    ],
    showReportDialog: false,
    selectedReportType: '',
    reportPostId: ''
  },

  onLoad() {
    this.initPage()
  },

  onShow() {
    // 页面显示时刷新动态
    this.loadPosts()
  },

  /**
   * 初始化页面
   */
  initPage() {
    // 获取用户当前城市
    this.getCurrentLocation()
    this.loadPosts()
  },

  /**
   * 获取当前定位
   */
  getCurrentLocation() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        // 根据经纬度获取城市名称
        this.getCityByLocation(res.latitude, res.longitude)
      },
      fail: () => {
        // 获取定位失败，使用默认城市
        console.log('获取定位失败，使用默认城市')
      }
    })
  },

  /**
   * 根据定位获取城市
   */
  getCityByLocation(latitude, longitude) {
    // TODO: 实现逆地理编码
    // 这里使用模拟数据
    this.setData({
      currentCity: '深圳'
    })
  },

  /**
   * 加载动态列表
   */
  loadPosts() {
    this.setData({ loading: true })
    
    const params = {
      filter: this.data.activeFilter,
      city: this.data.currentCity === '全国' ? '' : this.data.currentCity,
      keyword: this.data.searchKeyword
    }
    
    get('/api/community/posts', params)
      .then(data => {
        let posts = data.posts || []
        
        // 处理动态数据
        posts = posts.map(post => {
          return {
            ...post,
            // 格式化内容（处理话题和@提及）
            formattedContent: this.formatPostContent(post.content),
            // 判断是否为长文本
            isLongText: post.content && post.content.length > 100,
            isExpanded: false
          }
        })
        
        this.setData({
          posts,
          loading: false,
          refreshing: false
        })
      })
      .catch(error => {
        console.error('加载动态失败:', error)
        this.setData({ 
          loading: false,
          refreshing: false 
        })
        showError('加载失败，请重试')
      })
  },

  /**
   * 格式化动态内容
   */
  formatPostContent(content) {
    if (!content) return ''
    
    // 处理话题标签 #话题#
    content = content.replace(/#([^#\s]+)#/g, '<span style="color:#FF6B9D">#$1#</span>')
    
    // 处理@提及 @用户名
    content = content.replace(/@([\u4e00-\u9fa5\w]+)/g, '<span style="color:#FF6B9D">@$1</span>')
    
    return content
  },

  /**
   * 筛选标签切换
   */
  onFilterChange(e) {
    const activeFilter = e.currentTarget.dataset.filter
    this.setData({ activeFilter })
    this.loadPosts()
  },

  /**
   * 显示城市选择器
   */
  showLocationSelector() {
    this.setData({ showLocationPicker: true })
  },

  /**
   * 隐藏城市选择器
   */
  hideLocationPicker() {
    this.setData({ showLocationPicker: false })
  },

  /**
   * 选择城市
   */
  selectCity(e) {
    const { city, code } = e.currentTarget.dataset
    
    // 更新城市选择状态
    const cities = this.data.cities.map(item => ({
      ...item,
      selected: item.cityCode === code
    }))
    
    this.setData({
      currentCity: city,
      cities,
      showLocationPicker: false
    })
    
    // 重新加载动态
    this.loadPosts()
  },

  /**
   * 下拉刷新
   */
  onRefresh() {
    this.setData({ refreshing: true })
    this.loadPosts()
  },

  /**
   * 加载更多
   */
  onLoadMore() {
    if (!this.data.hasMore) return
    
    // TODO: 实现分页加载
    console.log('加载更多动态')
  },

  /**
   * 点赞动态
   */
  toggleLike(e) {
    const postId = e.currentTarget.dataset.postId
    const post = this.data.posts.find(p => p.postId === postId)
    
    if (!post) return
    
    const action = post.isLiked ? 'unlike' : 'like'
    
    post('/api/community/posts/' + action, { postId })
      .then(() => {
        // 更新本地状态
        post.isLiked = !post.isLiked
        post.likesCount += post.isLiked ? 1 : -1
        
        this.setData({ posts: this.data.posts })
      })
      .catch(error => {
        console.error('点赞操作失败:', error)
        showError('操作失败，请重试')
      })
  },

  /**
   * 显示评论弹窗
   */
  showCommentDialog(e) {
    const postId = e.currentTarget.dataset.postId
    this.setData({
      showCommentModal: true,
      currentPostId: postId,
      commentContent: ''
    })
  },

  /**
   * 隐藏评论弹窗
   */
  hideCommentModal() {
    this.setData({
      showCommentModal: false,
      currentPostId: '',
      commentContent: ''
    })
  },

  /**
   * 评论内容输入
   */
  onCommentInput(e) {
    this.setData({
      commentContent: e.detail.value
    })
  },

  /**
   * 发送评论
   */
  sendComment() {
    const { currentPostId, commentContent } = this.data
    
    if (!commentContent.trim()) {
      showError('请输入评论内容')
      return
    }
    
    post('/api/community/comments', {
      postId: currentPostId,
      content: commentContent.trim()
    })
      .then(() => {
        // 更新评论数
        const post = this.data.posts.find(p => p.postId === currentPostId)
        if (post) {
          post.commentsCount += 1
          this.setData({ posts: this.data.posts })
        }
        
        this.hideCommentModal()
        showSuccess('评论成功')
      })
      .catch(error => {
        console.error('发送评论失败:', error)
        showError('评论失败，请重试')
      })
  },

  /**
   * 分享动态
   */
  sharePost(e) {
    const postId = e.currentTarget.dataset.postId
    
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    
    // 更新分享数
    post('/api/community/posts/share', { postId })
      .then(() => {
        const post = this.data.posts.find(p => p.postId === postId)
        if (post) {
          post.sharesCount += 1
          this.setData({ posts: this.data.posts })
        }
      })
      .catch(error => {
        console.error('分享失败:', error)
      })
  },

  /**
   * 展开全文
   */
  expandPost(e) {
    const postId = e.currentTarget.dataset.postId
    const post = this.data.posts.find(p => p.postId === postId)
    
    if (post) {
      post.isExpanded = true
      this.setData({ posts: this.data.posts })
    }
  },

  /**
   * 搜索话题
   */
  searchTopic(e) {
    const topic = e.currentTarget.dataset.topic
    this.setData({
      searchKeyword: `#${topic}#`,
      showSearch: true
    })
    this.loadPosts()
  },

  /**
   * 查看提及的用户
   */
  viewMentionedUser(e) {
    const userId = e.currentTarget.dataset.userId
    navigateTo(`/pages/user-profile/user-profile?userId=${userId}`)
  },

  /**
   * 查看用户资料
   */
  viewUserProfile(e) {
    const userId = e.currentTarget.dataset.userId
    navigateTo(`/pages/user-profile/user-profile?userId=${userId}`)
  },

  /**
   * 关注/取消关注
   */
  toggleFollow(e) {
    const userId = e.currentTarget.dataset.userId
    const post = this.data.posts.find(p => p.author.userId === userId)
    
    if (!post) return
    
    const action = post.author.isFollowing ? 'unfollow' : 'follow'
    
    post(`/api/community/${action}`, { userId })
      .then(() => {
        post.author.isFollowing = !post.author.isFollowing
        this.setData({ posts: this.data.posts })
        
        showToast(post.author.isFollowing ? '已关注' : '已取消关注')
      })
      .catch(error => {
        console.error('关注操作失败:', error)
        showError('操作失败，请重试')
      })
  },

  /**
   * 显示动态菜单
   */
  showPostMenu(e) {
    const postId = e.currentTarget.dataset.postId
    const post = this.data.posts.find(p => p.postId === postId)
    
    if (!post) return
    
    let actions = []
    
    if (post.author.isSelf) {
      // 自己的动态
      actions = [
        { name: 'edit', text: '编辑' },
        { name: 'delete', text: '删除', color: '#ff3b30' }
      ]
    } else {
      // 他人的动态
      actions = [
        { name: 'report', text: '举报', color: '#ff3b30' },
        { name: 'block', text: '屏蔽该用户', color: '#ff3b30' }
      ]
    }
    
    this.setData({
      showActionSheet: true,
      actionSheetActions: actions,
      currentPostId: postId
    })
  },

  /**
   * 操作菜单选择
   */
  onActionSelect(e) {
    const { name } = e.detail
    
    switch (name) {
      case 'edit':
        this.editPost()
        break
      case 'delete':
        this.deletePost()
        break
      case 'report':
        this.reportPost()
        break
      case 'block':
        this.blockUser()
        break
    }
    
    this.hideActionSheet()
  },

  /**
   * 隐藏操作菜单
   */
  hideActionSheet() {
    this.setData({
      showActionSheet: false,
      currentPostId: ''
    })
  },

  /**
   * 编辑动态
   */
  editPost() {
    // TODO: 实现编辑功能
    showToast('编辑功能开发中')
  },

  /**
   * 删除动态
   */
  deletePost() {
    const { currentPostId } = this.data
    
    wx.showModal({
      title: '删除动态',
      content: '确定要删除这条动态吗？',
      confirmText: '删除',
      confirmColor: '#ff3b30',
      success: (res) => {
        if (res.confirm) {
          post('/api/community/posts/delete', { postId: currentPostId })
            .then(() => {
              // 从列表中移除
              const posts = this.data.posts.filter(p => p.postId !== currentPostId)
              this.setData({ posts })
              showSuccess('已删除')
            })
            .catch(error => {
              console.error('删除动态失败:', error)
              showError('删除失败，请重试')
            })
        }
      }
    })
  },

  /**
   * 举报动态
   */
  reportPost() {
    // TODO: 实现举报功能
    showToast('举报功能开发中')
  },

  /**
   * 屏蔽用户
   */
  blockUser() {
    // TODO: 实现屏蔽功能
    showToast('屏蔽功能开发中')
  },

  /**
   * 查看动态详情
   */
  viewPostDetail(e) {
    const postId = e.currentTarget.dataset.postId
    navigateTo(`/pages/post-detail/post-detail?postId=${postId}`)
  },

  /**
   * 创建动态
   */
  createPost() {
    this.setData({
      showCreatePost: true,
      newPostContent: '',
      canPublish: false,
      selectedTopics: [],
      selectedMentions: []
    })
  },

  /**
   * 隐藏创建动态弹窗
   */
  hideCreatePost() {
    this.setData({
      showCreatePost: false
    })
  },

  /**
   * 动态内容输入
   */
  onPostContentInput(e) {
    const content = e.detail.value
    this.setData({
      newPostContent: content,
      canPublish: content.trim().length > 0
    })
  },

  /**
   * 添加话题
   */
  addTopic() {
    // TODO: 实现话题选择功能
    showToast('话题选择功能开发中')
  },

  /**
   * 添加@提及
   */
  addMention() {
    // TODO: 实现@好友功能
    showToast('@好友功能开发中')
  },

  /**
   * 添加心情贴纸
   */
  addMoodSticker() {
    // TODO: 实现心情贴纸功能
    showToast('心情贴纸功能开发中')
  },

  /**
   * 添加位置
   */
  addLocation() {
    // TODO: 实现位置选择功能
    showToast('位置选择功能开发中')
  },

  /**
   * 发布动态
   */
  publishPost() {
    const { newPostContent, selectedTopics, selectedMentions } = this.data
    
    if (!newPostContent.trim()) {
      showError('请输入动态内容')
      return
    }
    
    const postData = {
      content: newPostContent.trim(),
      topics: selectedTopics,
      mentions: selectedMentions
    }
    
    post('/api/community/posts/create', postData)
      .then(data => {
        this.hideCreatePost()
        showSuccess('发布成功')
        
        // 刷新动态列表
        this.loadPosts()
      })
      .catch(error => {
        console.error('发布动态失败:', error)
        showError('发布失败，请重试')
      })
  },

  /**
   * 显示增强的发布编辑器
   */
  showPostEditor() {
    this.setData({
      showPostEditor: true,
      editorContent: '',
      inputTopics: [],
      inputMentions: [],
      postPrivacy: 'public',
      enableComments: true,
      enableSharing: true
    })
    
    // 加载热门话题
    this.loadHotTopics()
  },

  /**
   * 隐藏发布编辑器
   */
  hidePostEditor() {
    this.setData({ showPostEditor: false })
  },

  /**
   * 编辑器内容输入
   */
  onEditorInput(e) {
    const content = e.detail.value
    const cursor = e.detail.cursor
    
    this.setData({
      editorContent: content,
      editorCursorPosition: cursor
    })
    
    // 检测话题和提及
    this.detectHashtagsAndMentions(content)
  },

  /**
   * 检测话题和提及
   */
  detectHashtagsAndMentions(content) {
    // 提取话题
    const hashtagRegex = /#([^#\s]+)#/g
    const hashtags = []
    let match
    while ((match = hashtagRegex.exec(content)) !== null) {
      if (!hashtags.includes(match[1])) {
        hashtags.push(match[1])
      }
    }
    
    // 提取提及
    const mentionRegex = /@([\u4e00-\u9fa5\w]+)/g
    const mentions = []
    while ((match = mentionRegex.exec(content)) !== null) {
      if (!mentions.includes(match[1])) {
        mentions.push(match[1])
      }
    }
    
    this.setData({
      inputTopics: hashtags,
      inputMentions: mentions
    })
  },

  /**
   * 加载热门话题
   */
  loadHotTopics() {
    get('/api/community/topics/hot')
      .then(data => {
        this.setData({
          hotTopics: data.topics || []
        })
      })
      .catch(error => {
        console.error('加载热门话题失败:', error)
      })
  },

  /**
   * 显示话题选择器
   */
  showTopicSelector() {
    this.setData({ showTopicPicker: true })
  },

  /**
   * 隐藏话题选择器
   */
  hideTopicPicker() {
    this.setData({ showTopicPicker: false })
  },

  /**
   * 选择话题
   */
  selectTopic(e) {
    const topic = e.currentTarget.dataset.topic
    const { editorContent, editorCursorPosition } = this.data
    
    // 在光标位置插入话题
    const beforeCursor = editorContent.slice(0, editorCursorPosition)
    const afterCursor = editorContent.slice(editorCursorPosition)
    const newContent = `${beforeCursor}#${topic}# ${afterCursor}`
    
    this.setData({
      editorContent: newContent,
      showTopicPicker: false
    })
    
    // 重新检测话题和提及
    this.detectHashtagsAndMentions(newContent)
  },

  /**
   * 显示提及选择器
   */
  showMentionSelector() {
    this.setData({
      showMentionPicker: true,
      mentionSearchKeyword: ''
    })
    
    // 加载推荐用户
    this.loadMentionUsers()
  },

  /**
   * 隐藏提及选择器
   */
  hideMentionPicker() {
    this.setData({ showMentionPicker: false })
  },

  /**
   * 提及搜索输入
   */
  onMentionSearch(e) {
    const keyword = e.detail.value
    this.setData({ mentionSearchKeyword: keyword })
    
    // 搜索用户
    if (keyword.trim()) {
      this.searchMentionUsers(keyword)
    } else {
      this.loadMentionUsers()
    }
  },

  /**
   * 加载提及用户
   */
  loadMentionUsers() {
    get('/api/community/users/suggest')
      .then(data => {
        this.setData({
          mentionUsers: data.users || []
        })
      })
      .catch(error => {
        console.error('加载推荐用户失败:', error)
      })
  },

  /**
   * 搜索提及用户
   */
  searchMentionUsers(keyword) {
    get('/api/community/users/search', { keyword })
      .then(data => {
        this.setData({
          mentionUsers: data.users || []
        })
      })
      .catch(error => {
        console.error('搜索用户失败:', error)
      })
  },

  /**
   * 选择提及用户
   */
  selectMentionUser(e) {
    const { nickname } = e.currentTarget.dataset
    const { editorContent, editorCursorPosition } = this.data
    
    // 在光标位置插入提及
    const beforeCursor = editorContent.slice(0, editorCursorPosition)
    const afterCursor = editorContent.slice(editorCursorPosition)
    const newContent = `${beforeCursor}@${nickname} ${afterCursor}`
    
    this.setData({
      editorContent: newContent,
      showMentionPicker: false
    })
    
    // 重新检测话题和提及
    this.detectHashtagsAndMentions(newContent)
  },

  /**
   * 设置发布隐私
   */
  setPostPrivacy(e) {
    const privacy = e.detail.value
    this.setData({ postPrivacy: privacy })
  },

  /**
   * 切换评论权限
   */
  toggleComments(e) {
    this.setData({ enableComments: e.detail.value })
  },

  /**
   * 切换分享权限
   */
  toggleSharing(e) {
    this.setData({ enableSharing: e.detail.value })
  },

  /**
   * 发布增强动态
   */
  publishEnhancedPost() {
    const {
      editorContent,
      inputTopics,
      inputMentions,
      postPrivacy,
      enableComments,
      enableSharing,
      currentCity
    } = this.data
    
    if (!editorContent.trim()) {
      showError('请输入动态内容')
      return
    }
    
    const postData = {
      content: editorContent.trim(),
      topics: inputTopics,
      mentions: inputMentions,
      privacy: postPrivacy,
      enableComments,
      enableSharing,
      location: currentCity !== '全国' ? currentCity : null
    }
    
    post('/api/community/posts/create', postData)
      .then(data => {
        this.hidePostEditor()
        showSuccess('发布成功')
        
        // 刷新动态列表
        this.loadPosts()
      })
      .catch(error => {
        console.error('发布动态失败:', error)
        showError('发布失败，请重试')
      })
  },

  /**
   * 加载附近动态
   */
  loadNearbyPosts() {
    // 获取当前位置
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({ userLocation: res })
        
        const params = {
          latitude: res.latitude,
          longitude: res.longitude,
          maxDistance: this.data.maxDistance
        }
        
        get('/api/community/posts/nearby', params)
          .then(data => {
            this.setData({
              nearbyPosts: data.posts || []
            })
          })
          .catch(error => {
            console.error('加载附近动态失败:', error)
          })
      },
      fail: () => {
        showError('需要定位权限才能查看附近动态')
      }
    })
  },

  /**
   * 设置附近距离
   */
  setMaxDistance(e) {
    const distance = e.detail.value
    this.setData({ maxDistance: distance })
    
    // 重新加载附近动态
    if (this.data.userLocation) {
      this.loadNearbyPosts()
    }
  },

  /**
   * 显示话题详情
   */
  showTopicDetails(e) {
    const topic = e.currentTarget.dataset.topic
    
    this.setData({
      showTopicDetail: true,
      currentTopic: topic
    })
    
    // 加载话题相关动态
    this.loadTopicPosts(topic)
  },

  /**
   * 隐藏话题详情
   */
  hideTopicDetail() {
    this.setData({
      showTopicDetail: false,
      currentTopic: null,
      topicPosts: []
    })
  },

  /**
   * 加载话题相关动态
   */
  loadTopicPosts(topic) {
    get('/api/community/topics/posts', { topic })
      .then(data => {
        this.setData({
          topicPosts: data.posts || []
        })
      })
      .catch(error => {
        console.error('加载话题动态失败:', error)
      })
  },

  /**
   * 显示用户操作菜单
   */
  showUserActionMenu(e) {
    const userId = e.currentTarget.dataset.userId
    const user = e.currentTarget.dataset.user
    
    this.setData({
      showUserActions: true,
      selectedUser: { userId, ...user }
    })
  },

  /**
   * 隐藏用户操作菜单
   */
  hideUserActions() {
    this.setData({
      showUserActions: false,
      selectedUser: null
    })
  },

  /**
   * 照片动态私聊
   */
  chatWithUser() {
    const { selectedUser } = this.data
    if (!selectedUser) return
    
    // 跳转到聊天页面
    navigateTo(`/pages/chat/chat?userId=${selectedUser.userId}`)
    this.hideUserActions()
  },

  /**
   * 查看用户详情
   */
  viewUserDetails() {
    const { selectedUser } = this.data
    if (!selectedUser) return
    
    navigateTo(`/pages/user-detail/user-detail?userId=${selectedUser.userId}`)
    this.hideUserActions()
  },

  /**
   * 显示举报对话框
   */
  showReportDialog(e) {
    const postId = e.currentTarget.dataset.postId
    
    this.setData({
      showReportDialog: true,
      reportPostId: postId,
      selectedReportType: ''
    })
  },

  /**
   * 选择举报类型
   */
  selectReportType(e) {
    const type = e.currentTarget.dataset.type
    this.setData({ selectedReportType: type })
  },

  /**
   * 提交举报
   */
  submitReport() {
    const { reportPostId, selectedReportType } = this.data
    
    if (!selectedReportType) {
      showError('请选择举报类型')
      return
    }
    
    post('/api/community/posts/report', {
      postId: reportPostId,
      type: selectedReportType
    })
      .then(() => {
        this.setData({
          showReportDialog: false,
          reportPostId: '',
          selectedReportType: ''
        })
        showSuccess('举报已提交，我们将尽快处理')
      })
      .catch(error => {
        console.error('举报失败:', error)
        showError('举报失败，请重试')
      })
  },

  /**
   * 取消举报
   */
  cancelReport() {
    this.setData({
      showReportDialog: false,
      reportPostId: '',
      selectedReportType: ''
    })
  },

  /**
   * 分享页面
   */
  onShareAppMessage() {
    return {
      title: '青鸟笺社区 - 分享你的美好生活',
      path: '/pages/community/community',
      imageUrl: '../../images/share-community.png'
    }
  }
})